package com.ignou.mca.login;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ignou.mca.beans.RegistrationVO;
import com.ignou.mca.datasource.DatabaseOperations;
import com.ignou.mca.utils.RandamNumberGeneration;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() 
    {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		 String userName = request.getParameter("userName");
		 String password = request.getParameter("password");
		 String firstName = request.getParameter("firstName");
		 String lastName = request.getParameter("lastName");
		 String email = request.getParameter("emailId");
		 String phone = request.getParameter("phone");
		 String address1 = request.getParameter("add1");
		 String address2 = request.getParameter("add2");
		 String city = request.getParameter("city");
		 String state = request.getParameter("state");
		 String country = request.getParameter("country");
		 String randomNumber = RandamNumberGeneration.randomstring(2, 5);
		 Date activationDate = new Date();
		 String securityQuestion=request.getParameter("securityQuestion");
		 String securityAnswer = request.getParameter("securityAnswer");
		 
		 ServletContext ctx = getServletContext();
		 
		 RegistrationVO rVo = new RegistrationVO();
		 rVo.setUserName(userName);
		 rVo.setPassword(password);
		 rVo.setFirstName(firstName);
		 rVo.setLastName(lastName);
		 rVo.setEmail(email);
		 rVo.setPhone(phone);
		 rVo.setAddress1(address1);
		 rVo.setAddress2(address2);
		 rVo.setCity(city);
		 rVo.setState(state);
		 rVo.setCountry(country);
		 rVo.setActiveStatus("1");
		 rVo.setActivationDate(activationDate);
		 rVo.setRole("1");
		 rVo.setRandomNumber(randomNumber);
		 rVo.setSecurityAnswer(securityAnswer);
		 rVo.setSecurityQuestion(securityQuestion);
		
		 DatabaseOperations dbOperations = new DatabaseOperations();
		 Boolean isRegistrationSuccess = dbOperations.doRegistration(rVo,"http://localhost:8080/OES/UserActivation.do");
		 if(isRegistrationSuccess==true)
		 {
			 response.sendRedirect("./UserActivation.jsp");
		 }
		 else
		 {
			 request.setAttribute("ErrorMessage", "Unable to register at this time. Please try again after some time.");
			 ctx.getRequestDispatcher("/ErrorDisplay.jsp").forward(request, response);
		 }
	}
}
